"""

数据库执行公共函数

"""
import os
import time

from yat.test import macro

from .Constant import Constant
from .Logger import Logger


class CommonLite:
    def __init__(self,node):
        """
        初始化
        :param node_name: 通过root用户还是数据库安装的用户执行脚本（见 conf/nodes.yml）
        """
        self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.log = Logger()
        self.Constant = Constant()
        self.node = node



    def execute_gsguc(self, command, assert_flag, param, node_name='all',
                      get_detail=False, single=False, dn_path='',
                      pghba_param='', env_path=macro.DB_ENV_PATH):
        """
        gs_guc工具
        :param command: 例如'check'
        :param assert_flag: 例如self.Constant.GSGUC_SUCCESS_MSG
        :param param: 例如'max_connections'
        :param node_name: 节点名
        :param get_detail: True返回详细信息，False返回bool值
        :param single: True代表仅在本节点执行gs_guc命令，False在所有节点执行gs_guc命令
        :param dn_path: 可指定数据目录
        :param pghba_param: 适配修改pg_hba
        :return: 返回执行结果
        """
        if not dn_path:
            dn_path = self.DB_INSTANCE_PATH
        self.log.info("----gs_guc start execute----")
        if single:
            if pghba_param:
                gs_guc_cmd = f'source {env_path}; ' \
                    f'gs_guc {command} ' \
                    f'-D {dn_path} ' \
                    f'-h "{pghba_param}";'
            else:
                gs_guc_cmd = f'source {env_path}; ' \
                    f'gs_guc {command} ' \
                    f'-D {dn_path} ' \
                    f'-c "{param}";'
        else:
            if pghba_param:
                gs_guc_cmd = f'source {env_path}; ' \
                    f'gs_guc {command} ' \
                    f'-N {node_name} ' \
                    f'-D {dn_path} ' \
                    f'-h "{pghba_param}";'
            else:
                gs_guc_cmd = f'source {env_path}; ' \
                    f'gs_guc {command} ' \
                    f'-N {node_name} ' \
                    f'-D {dn_path} ' \
                    f'-c "{param}";'
        self.log.info(gs_guc_cmd)
        show_msg = self.node.sh(gs_guc_cmd).result()
        self.log.info(show_msg)
        if command == 'reload':
            time.sleep(5)
        if get_detail:
            return show_msg
        else:
            return show_msg.find(assert_flag) > -1


    def execut_db_sql(self, sql, sql_type='', dbname=None,
                      env_path=macro.DB_ENV_PATH):
        """
        使用gsql的方式调用数据库sql语句
        :param sql: sql语句
        :param sql_type: 参数？
        :param dbname: 库名
        :return:
        """
        if dbname is None:
            database_name = self.node.db_name
        else:
            database_name = dbname
        shell = f'source {env_path}; ' \
            f'gsql -d {database_name} ' \
            f'-p {self.node.db.port} ' \
            f'-r ' \
            f'{sql_type} ' \
            f'-c "{sql}" '
        msg = self.node.sh(shell).result()
        self.log.info(shell)
        return msg




    def execute_generate(self, factor, prefix='subscription',
                         path='$GAUSSHOME/bin',
                         env_path=macro.DB_ENV_PATH):
        """
        执行gs_guc generate
        prefix:前缀
        factor:加密因子
        path:生成路径
        :return:
        """
        cmd = f"source {env_path};" \
            f"gs_guc generate -S {factor} -D {path} -o {prefix}"
        self.log.info(cmd)
        result = self.node.sh(cmd).result()
        self.log.info(result)
        return result




    def show_param(self, guc_param, env_path=macro.DB_ENV_PATH):
        """
        function:查看guc参数默认值
        :param guc_param: guc参数
        :param env_path: 环境变量路径
        :return: 返回参数默认值
        """
        check_default = f'show {guc_param};'
        default_msg = CommonLite(self.node).execut_db_sql(check_default, '',
                                                  None, env_path)
        self.log.info(default_msg)
        default_msg_list = default_msg.splitlines()[-2].strip()
        self.log.info(default_msg_list)
        return default_msg_list




    def stop_db_instance(self, env_path=macro.DB_ENV_PATH,
                         dn_path=macro.DB_INSTANCE_PATH,
                         param=''):
        """
        停止数据库实例
        """
        self.log.error("==stop_db_instance==")
        msg = self.node.sh('source {};gs_ctl stop -D {} {}'.format(
            env_path, dn_path, param)).result()
        self.log.info(msg)
        time.sleep(3)
        return msg




    def start_db_instance(self, mode="primary", env_path=macro.DB_ENV_PATH,
                          dn_path=macro.DB_INSTANCE_PATH):
        """
        启动数据库实例
        :param mode: primary or standby
        """
        self.log.error("==start_db_instance==")
        msg = self.node.sh('source {};gs_ctl start -D {} -M {}'.format(
            env_path, dn_path, mode)).result()
        self.log.info(msg)
        time.sleep(10)
        return msg

